from flask import Blueprint,Response
from flask import render_template
from flask import request
from flask import jsonify
from flask import session
from flask import redirect
from flask import abort

from flask_login import LoginManager,UserMixin,login_required
from werkzeug.wrappers import Response
from admin.core.auth import logon_check, permission_check
import json
import hashlib
from models.entity.department import Department
from models.entity.organization import Organization
from models.entity.point import Point
from models.entity.quarter import Quarter
from models.entity.role import Role
from models.entity.button import Button
from models.entity.token import Token
from models.entity.user import User
from models.entity.role_with_user import RoleWithUser
from models.entity.role_with_button import RoleWithButton
from models.entity.module import Module
from models.view.auth import AuthLogicalModel
from utils.nodetree import get_all_model
from appserver import execute_sql
from utils.result import result
from flask.views import MethodView,View
from flask_debugtoolbar import DebugToolbarExtension
from flask_security import RoleMixin
from flask_restful import Resource,Api,reqparse,fields,marshal,marshal_with,marshal_with_field
# /core/user/add_role_to_users/
mod = Blueprint("user", __name__, url_prefix="/core/user", template_folder="templates", static_folder="static")

@mod.route("/", methods=["GET", "POST"])
def index():
    return render_template("home/employeesManagementT.html")


@mod.route("/login/", methods=["GET", "POST"])
def login():
    # GET方式:
    # 返回html
    # POST方式:
    # request: form
    #       username:"username",
    #       password:"password"
    # return: json
    # {
    #       success:1,
    #       error_code:null,
    #       error_msg:null,
    #       data:[{
    #               username:"username",
    #               token:"token"
    #            }]
    # }
    if request.method == "GET":
        return render_template("home/logon.html")
    if request.method == "POST":
        username = request.form.get("username", "")
        print(111,username)
        password = request.form.get("password", "")
        print(222, password)

    # 这个是我做的post请求接收数据的方式,上面是用fromdata请求
    # if request.method == "POST":
    #     data = json.loads(request.data.decode("utf-8"))
    #     username = data['username']
    #     print(111, username)
    #     password = data.get("password", "")
    #     print(222, password)


        if username is None or username == "":
            return result(success=0, error_code=-3, error_msg="用户名不能为空")
        if password is None or password == "":
            error_msg = {
                "success": 0,
                "error_code": -4,
                "error_msg": "密码不能为空"
            }
            return jsonify(error_msg)
        ret = User.verify_user(username, password)
        if ret == -1:
            error_msg = {
                "success": 0,
                "error_code": -5,
                "error_msg": "该用户名不存在"
            }
            return jsonify(error_msg)
        if ret == -2:
            error_msg = {
                "success": 0,
                "error_code": -6,
                "error_msg": "密码错误"
            }
            return jsonify(error_msg)
        the_user = User.get_user_by_username(username)
        # the_token = None
        if ret == 0:
            rdic = {
                "success": 1,
                "error_code": None,
                "error_msg": None
            }
            rdic["data"] = [{}]
            rdic["data"][0]["username"] = username
            rdic["data"][0]["safe_code"] = the_user.safe_code
            rdic["data"][0]["id"] = the_user.id
            # 登录之前注销该用户所有的token
            token_list = Token.get_tokens_by_user_id(the_user.id)
            print('token_list', token_list)
            if len(token_list) != 0:
                for item in token_list:

                    if Token.destory_token(item.token) != 0:
                        # 如果删除失败
                        error_msg = {
                            "success": 0,
                            "error_code": -9,
                            "error_msg": "token destory error"
                        }
                        return jsonify(error_msg)
                    else:
                        # error_msg = {
                        #     "success": 1,
                        #     "error_code": 0,
                        #     "error_msg": "token destory succeed"
                        # }
                        # return jsonify(error_msg)
                        pass
            # 建立新的token
            the_token = Token.generate_token_by_user(the_user)
            print(7777, the_token)
            if the_token.save()!=0:
                error_msg = {
                    "success":0,
                    "error_code":-9,
                    "error_msg":"token save error"
                }
                return jsonify(error_msg)
            print(999)
            auth_obj = AuthLogicalModel(the_token)
            print(888)
            session["auth"] = auth_obj.get_dic()
            if the_token == -1 or the_token == -2:
                error_msg = {
                    "success": 0,
                    "error_code": -7,
                    "error_msg": "generate token error"
                }
                return jsonify(error_msg)
            rdic["data"][0]["token"] = the_token.token
            target_url = request.args.get("next", None)
            if not target_url is None:
                rdic["next"] = target_url
            else:
                rdic["next"] = None
            return jsonify(rdic)
        error_msg = {
            "success": 0,
            "error_code": -8,
            "error_msg": "unknow error"
        }
        return jsonify(error_msg)
    # 若以POST和GET以外的方式访问
    return abort(405)


@mod.route("/test1/", methods=["GET"])
@logon_check
@permission_check
def test():
    return "done"


@mod.route("/add_user/", methods=["GET", "POST"])
def add_user_interface():
    """
    添加用户
    """
    # request: json
    """data {'organization_id': 1, 'email': '2312', 'job_number': '213', 'phone_number': '31', 'quarter_id': 1,
    'description': '', 'roles_id': [1], 'password': '123123', 'department_id': 1, 'safe_code': '213',
    'username': '1231', 'status': 1, 'sex': 1}
    """

    try:
        if request.method == 'POST':
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error",
        }
        return jsonify(error_msg)
    try:
        # print(111111111,data)
        username = data["username"]
        password = data["password"]
    except Exception as err:
        print(err)
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    if not User.get_user_by_username(data["username"]) is None:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "该账户已被注册"
        }
        return jsonify(error_msg)
    if User.check_user_email(data["email"]):
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "该邮箱已被注册"
        }
        return jsonify(error_msg)
    in_dic = {}
    in_dic["username"] = username
    in_dic["password"] = password
    in_dic["email"] = data["email"]
    if User.check_user_phone_number(data["phone_number"]):
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "该手机号码已被注册"
        }
        return jsonify(error_msg)
    in_dic["phone_number"] = data["phone_number"]
    in_dic["safe_code"] = data["safe_code"]
    in_dic["job_number"] = data["job_number"]
    in_dic["sex"] = data["sex"]
    # in_dic["organization_id"] = data["organization_id"]
    in_dic["organization_id"] = data.get("organization_id", None)
    in_dic["quarter_id"] = data.get("quarter_id", None)
    # in_dic["organization_id"] = data["organization_id"]
    if "department_id" in data:  # 根据dep的外键来确定修改org_id
        in_dic["organization_id"] = Organization.get_organization_by_department_id(
        data["department_id"])
    in_dic["department_id"] = data.get("department_id", None)
    in_dic["roles_id"] = data["roles_id"]
    # for item in roles_id:
    #     the_role = Role.get_role_by_id(item)
    #     in_dic["roles"].append(the_role)
    # for role in roles_id:
    #     if not isinstance(role, int):
    #         error_msg = {
    #             "success": 0,
    #             "error_code": -6,
    #             "error_msg": "role_id must be an int"
    #         }
    #         return jsonify(error_msg)
    #     User.add_roles_to_user()
        # t_role = Role.get_role_by_id(role)
        # if not t_role:
        #     error_msg = {
        #         "success": 0,
        #         "error_code": -7,
        #         "error_msg": "role(id=%d) is not exist" % role
        #     }
        #     return jsonify(error_msg)
        # if User.add_roles_to_user(the_user, [t_role]) != 0:
        #     error_msg = {
        #         "success": 0,
        #         "error_code": -8,
        #         "error_msg": "build relationship between user(id=%d) and role(id=%d)" % (the_user.id, t_role.id)
        #     }
        #     return jsonify(error_msg)



    in_dic["description"] = data["description"]
    in_dic["status"] = data["status"]
    try:
        User.add_user(in_dic)
    except RuntimeError as err:
        rdic = {
            "success": 0,
            "error_code": -2,
            "error_msg": str(err),
            "data": []
        }
        return jsonify(rdic)
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": []
    }
    return jsonify(rdic)
    # if isinstance(ret_user, int):
    #     print("add_user_interface error")
    #     rdic = {
    #         "success": 0,
    #         "error_code": -2,
    #         "error_msg": "Unknow Error",
    #         "data": []
    #     }
    #     return jsonify(rdic)
    # t_dic = User.get_user_dic(ret_user)
    # t_dic.pop("password")
    # rdic = {
    #     "success": 1,
    #     "error_code": None,
    #     "error_msg": None,
    #     "data": [t_dic]
    # }
    # return jsonify(rdic)


@mod.route("/change_password/", methods=["POST"])
# @logon_check      # 这个方法加上之后就没有session['auth]这个token,之后再研究
def change_password_interface():
    """
    更改特定用户的密码
    """
    # request: json
    # {
    #       user_id: user_id,
    #       old_password: "old_password",
    #       new_password: "new_password",
    #       repassword: "repassword"
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    if not "user_id" in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "user_id is not in the json"
        }
        return jsonify(error_msg)
    else:
        user_id = data["user_id"]
    if not "new_password" in data:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "new_password is not in the json"
        }
        return jsonify(error_msg)
    else:
        new_password = data["new_password"]
    if not "repassword" in data:
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "repassword is not in the json"
        }
        return jsonify(error_msg)
    else:
        repassword = data["repassword"]
    if not "old_password" in data:
        error_msg = {
            "success": 0,
            "error_code": -8,
            "error_msg": "old_password is not in the json"
        }
        return jsonify(error_msg)
    else:
        old_password = data["old_password"]
    # print(11111111)
    # the_user = get_user_by_id_interface
    # the_user = User.get_user_by_id(user_id)
    username = User.get_user_by_id(user_id).username
    print('username', username)
    # 验证用户密码是否正确
    verify_result = User.verify_user(username, old_password)
    if verify_result != 0:
        if verify_result == -1:
            error_msg = {
                "success": 0,
                "error_code": -9,
                "error_msg": "指定用户不存在"
            }
            return jsonify(error_msg)
        else:
            error_msg = {
                "success": 0,
                "error_code": -9,
                "error_msg": "用户密码错误"
            }
            return jsonify(error_msg)
    if new_password != repassword:
        error_msg = {
            "success": 0,
            "error_code": -5,
            "error_msg": "两次密码输入不一致"
        }
        return jsonify(error_msg)
    the_user = User.get_user_by_id(user_id)
    # print('the_user', the_user)
    if the_user is None:
        error_msg = {
            "success": 0,
            "error_code": -6,
            "error_msg": "the user is not exist"
        }
        return jsonify(error_msg)
    # the_user.password = hashlib.md5(user_dic["password"].encode("utf-8")).hexdigest()
    # the_user.password = hashlib.md5(the_user.password.encode("utf-8")).hexdigest()
    new_password = hashlib.md5(new_password.encode("utf-8")).hexdigest() # 新密码做hash
    print('new_password', new_password)
    print(2222)
    # User.get_user_dic(the_user)
    the_user.password = new_password
    print('********')
    if the_user.save() != 0:
        print(333)
        error_msg = {
            "success": 0,
            "error_code": -7,
            "error_msg": "user save error"
        }
        return jsonify(error_msg)
    error_msg = {
        "success": 1,
        "error_code": None,
        "error_msg": None
    }
    return jsonify(error_msg)


# @mod.route("/login/",methods=["POST"])
# def login():
# request: form
#       username:"username",
#       password:"password"
# return: json
# {
#       success:1,
#       error_code:null,
#       error_msg:null,
#       data:[{
#               username:"username",
#               token:"token"
#            }]
# }
# try:
#     data=json.loads(request.data.decode("utf-8"))
# except:
#     error_msg={
#                     "success":0,
#                     "error_code":-1,
#                     "error_msg":"json format error"
#             }
#     return jsonify(error_msg)
# try:
#     username=data["username"]
#     password=data["password"]
# except:
#     error_msg={
#                     "success":0,
#                     "error_code":-2,
#                     "error_msg":"json key is not complete",
#             }
#     return jsonify(error_msg)


@mod.route("/logout/", methods=["GET","POST"])
def logout():
    """
    注销token
    """
    if not "auth" in session:
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "用户未登录"
        }
        return jsonify(error_msg)
    if Token.destory_token(session["auth"]["token"]) != 0:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "destory token error"
        }
        return jsonify(error_msg)
    # 从session中弹出当前用户
    session.pop("auth")
    error_msg = {
        "success": 1
    }
    return redirect("/core/user/login/")
    # return jsonify(error_msg)

@mod.route("/get_buttons_by_token/", methods=["GET", "POST"])
def get_buttons_by_token_local_interface():
    """
    获取该token能访问的所有button
    """
    # return: json
    # {
    #       success:1,
    #       error_code:null,
    #       error_msg:null,
    #       data:[button_id_1,button_id_2,...]
    # }
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": []
    }
    for item in session["auth"]["buttons"]:
        # print('item',item)
        rdic["data"].append(item)
    return jsonify(rdic)


@mod.route("/get_modules_by_token/", methods=["GET", "POST"])
def get_modules_by_token_local_interface():
    """
    以嵌套列表方式获取该token有权限访问的所有模块的树形结构
    """
    # return: json
    # {
    #       success:1,
    #       error_code:null,
    #       error_msg:null,
    #       data:[
    #                   {
    #                           id:id,
    #                           name:"name",
    #                           code:"code",
    #                           description:"description",
    #                           parent_id:parent_id,
    #                           path:path,
    #                           depth:depth,
    #                           child_num:child_num,
    #                           dis_order:dis_order,
    #                           target:"target",
    #                           url:"url",
    #                           icon:"icon",
    #                           is_menu:is_menu(int),
    #                           is_public:is_public(int),
    #                           is_expand:is_expand(int),
    #                           status:status
    #                           children: [
    #                                           {
    #                                                   id:id,
    #                                                   name:"name",
    #                                                   code:"code",
    #                                                   description:"description",
    #                                                   parent_id:parent_id,
    #                                                   path:path,
    #                                                   depth:depth,
    #                                                   child_num:child_num,
    #                                                   dis_order:dis_order,
    #                                                   target:"target",
    #                                                   url:"url",
    #                                                   icon:"icon",
    #                                                   is_menu:is_menu(int),
    #                                                   is_public:is_public(int),
    #                                                   is_expand:is_expand(int),
    #                                                   status:status
    #                                           }, ...
    #                                     ]
    #                   }, ...
    #            ]
    # }
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None
    }
    print('session["auth"]["modules"]', session["auth"]["modules"])
    rdic["data"] = get_all_model(session["auth"]["modules"], 0)
    return jsonify(rdic)


@mod.route("/get_module_all_by_token/", methods=["GET", "POST"])
def get_module_all_by_token_local_interface():
    """
    以平铺方式返回该token有权限访问的所有模块
    """
    # return: json
    # [
    #   {
    #       id:id,
    #       name:"name",
    #       code:"code",
    #       description:"description",
    #       ParentId:ParentId,
    #       path:"path",
    #       Level:Level,
    #       child_num:child_num,
    #       dis_order:dis_order,
    #       target:"target",
    #       url:"url",
    #       icon:"icon",
    #       is_menu:is_menu,
    #       is_public:is_public,
    #       is_expand:is_expand,
    #       status:status
    #   }, ...
    # ]
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": []
    }
    module_list = session["auth"]["modules"]
    for item in module_list:
        rdic["data"].append(item)
    return jsonify(rdic)


@mod.route("/get_user_all/", methods=["GET", "POST"])
def get_user_all_interface():
    """
    获取所有用户
    """
    # return: json
    # [
    #       {
    #               username: "username",
    #               email: "email",
    #               mobile_phone: "mobile_phone",
    #               password: "password",
    #               safe_code: "safe_code",
    #               sex: sex(int), // 1: 男性 0:女性
    #               department_id: department_id,
    #               organization_id: organization_id,
    #               roles: ["<role1>","<role2>",...]
    #       }, ...
    # ]
    rlist = []
    all_user_list = User.get_user_all()
    for the_user in all_user_list:
        tdic = User.get_user_dic(the_user)
        tdic["roles"] = []
        all_role_list = Role.get_roles_by_user(the_user)
        for item in all_role_list:
            print('item-all_role_list',item)
            print(type(item))
            # tdic["roles"].append(str(item))
            tdic["roles"].append(repr(item))
        rlist.append(tdic)
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": rlist
    }
    return jsonify(rdic)


@mod.route("/get_user_by_id/", methods=["GET", "POST"])
def get_user_by_id_interface():
    """
    根据用户id获取指定用户的信息
    """
    # request: json
    # {
    #       user_id: user_id
    # }
    # return: json
    # {
    #       username: "username",
    #       email: "email",
    #       mobile_phone: "mobile_phone",
    #       password: "password",
    #       safe_code: "safe_code",
    #       sex: sex(int), // 1:男性 0:女性
    #       department_id: department_id,
    #       roles: ["<role1>","<role2>",...]
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    if not "user_id" in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    the_user = User.get_user_by_id(data["user_id"])
    if not the_user:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "user(id=%d) is not exist" % (data["user_id"])
        }
        return jsonify(error_msg)
    t_dic = User.get_user_dic(the_user)
    # 从返回数据中弹出用户密码
    t_dic.pop("password")
    t_dic["roles"] = []
    all_role_list = Role.get_roles_by_user(the_user)
    for item in all_role_list:
        t_dic["roles"].append(str(item))
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": [t_dic]
    }
    return jsonify(rdic)


@mod.route("/get_user_by_token/", methods=["GET", "POST"])
def get_user_by_token_interface():
    """
    根据token获取用户信息
    """
    # the_user = User.get_user_by_id(session["auth"]["user_id"])
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
        id = data["id"]
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    the_user = User.get_user_by_id(id)
    t_dic = User.get_user_dic(the_user)
    # org_id = t_dic.pop("organization_id")
    # department_id = t_dic.pop("department_id")
    org_id = t_dic['organization_id']
    department_id = t_dic['department_id']
    if org_id!=None:
        the_organization = Organization().get_entity_by_id(org_id)
        t_dic["organization"] = the_organization.name
    else:
        t_dic["organization"] = None
    if department_id!=None:
        the_department = Department().get_entity_by_id(department_id)
        t_dic["department_name"] = the_department.name
    else:
        t_dic["department_name"] = None
    # 从返回数据中弹出用户密码
    t_dic.pop("password")
    t_dic["roles"] = []
    # for item in session["auth"]["roles"]:
    #     t_dic["roles"].append(item["name"])
    # t_dic["roles"] = [Role.get_role_dic(item) for item in Role.get_roles_by_user_id(id)]
    t_dic["roles"] = [item.id for item in Role.get_roles_by_user_id(id)]
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": [t_dic]
    }
    return jsonify(rdic)


@mod.route("/edit_user/", methods=["POST"])
def edit_user_interface():
    """
    编辑用户
    """
    # request: json
    # {
    #       id:id,
    #       username:"username",
    #       email:"email",
    #       phone_number:"phone_number",
    #       safe_code:"safe_code",
    #       sex: sex(int), // 1:男性 0:女性
    #       department_id:department_id,
    #       organization_id:organization_id
    #  data {'-----quarter_name': '值夜班', 'status': 0, 'sex': 1, 'department_name': '测试部门', 'safe_code': '1112',
    # 'department_id': 1, 'email': 'hrui2@163.com2', 'phone_number': '15835122123', 'id': 59,
    # '-----roles': ['111', '测试角色', 'min_role'], 'organization_id': 1, 'username': 'test31', 'quarter_id': 1,
    #  'roles_id': [5, 1, 2], 'job_number': '1232123123', 'description': '11112312',
    # 'password': '827ccb0eea8a706c4c34a16891f84e7b'}

    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    try:
        id_num = data["id"]
        username = data["username"]
        email = data["email"]
        phone_number = data["phone_number"]
        safe_code = data["safe_code"]
        sex = data["sex"]
        department_id = data["department_id"]
        organization_id = data["organization_id"]
        roles_id = data["roles_id"]
        description = data["description"]
        # password = data["password"]
        job_number = data["job_number"]
        status = data["status"]
        quarter_id = data["quarter_id"]
    except Exception as e:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        print(e)
        return jsonify(error_msg)
    the_user = User.get_user_by_id(id_num)
    if the_user is None:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "该用户不存在"
        }
        return jsonify(error_msg)
    if username != the_user.username:
        if not User.get_user_by_username(username) is None:
            error_msg = {
                "success": 0,
                "error_code": -4,
                "error_msg": "该账户已存在"
            }
            return jsonify(error_msg)
        the_user.username = username

###########我的想法还是简单了,不好,上面的更优
    # if username == the_user.username:
    #     error_msg = {
    #         "success": 0,
    #         "error_code": -4,
    #         "error_msg": "该用户名已存在"
    #     }
    #     return jsonify(error_msg)
    # the_user.username = username
##################
    if email != the_user.email:
        if not User.get_user_by_email(email) is None:
            error_msg = {
                "success": 0,
                "error_code": -5,
                "error_msg": "该邮箱已被注册"
            }
            return jsonify(error_msg)
        the_user.email = email
    if phone_number != the_user.phone_number:
        if not User.get_user_by_phone_number(phone_number) is None:
            error_msg = {
                "success": 0,
                "error_code": -6,
                "error_msg": "该手机号码已被注册"
            }
            return jsonify(error_msg)
        the_user.phone_number = phone_number
    if safe_code != the_user.safe_code:
        if not User.get_user_by_safe_code(safe_code) is None:
            error_msg = {
                "success": 0,
                "error_code": -7,
                "error_msg": "该姓名已存在"
            }
            return jsonify(error_msg)
        the_user.safe_code = safe_code
    if department_id != the_user.department_id:
        the_department = Department().get_entity_by_id(department_id)
        if the_department is None:
            error_msg = {
                "success": 0,
                "error_code": -8,
                "error_msg": "department is not exist"
            }
            return jsonify(error_msg)
        the_user.department_id = department_id
    if organization_id != the_user.organization_id:
        # get_organization_by_id  没有这个方法所以报错
        the_organization = Organization.get_organization_by_id(organization_id)
        if the_organization is None:
            error_msg = {
                "success": 0,
                "error_code": -9,
                "error_msg": "organization is not exist"
            }
            return jsonify(error_msg)
        the_user.organization_id = organization_id
    """
    data {'description': '111', 'password': '82', 'phone_number': '15835122123', 'username': 'test31',
     'job_number': '1232', 'id': 59, 'department_id': 1, 'roles_id': [1, 2], 'organization_id': 1, 'sex': '0',
     'status': 1, 'email': 'hrui2@163.com2', 'quarter_id': 1, 'safe_code': '1112'}
    """
    the_user.sex = sex
    the_user.quarter_id = quarter_id
    the_user.status = status
    the_user.job_number = job_number
    the_user.description = description
    connectors = RoleWithUser.query.filter_by(user_id=id_num).all()
    for item in connectors:
        if item.delete() != 0:
            return jsonify('删除错误')

    # RoleWithUser.add_roles_to_user(role_id, module_ids)
    for role in roles_id:
        if not isinstance(role, int):
            error_msg = {
                "success": 0,
                "error_code": -6,
                "error_msg": "role_id must be an int"
            }
            return jsonify(error_msg)
        t_role = Role.get_role_by_id(role)
        if not t_role:
            error_msg = {
                "success": 0,
                "error_code": -7,
                "error_msg": "role(id=%d) is not exist" % role
            }
            return jsonify(error_msg)
        if User.add_roles_to_user(the_user, [t_role]) != 0:
            error_msg = {
                "success": 0,
                "error_code": -8,
                "error_msg": "build relationship between user(id=%d) and role(id=%d)" % (the_user.id, t_role.id)
            }
            return jsonify(error_msg)

    # User().from_dict(data)
    # User.get_user_dic(the_user)
    ret = the_user.save()
    if ret != 0:
        error_msg = {
            "success": 0,
            "error_code": -10,
            "error_msg": "user save error"
        }
        return jsonify(error_msg)
    error_msg = {
        "success": 1
    }
    return jsonify(error_msg)


@mod.route("/delete_user_by_id/", methods=["POST"])
def delete_user_by_id_interface():
    """
    根据指定id删除某个用户
    """
    # request: json
    # {
    #       id: id
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
        # data = json.loads(bytes.decode(request.data))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    if not "id" in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    the_user = User.get_user_by_id(data["id"])
    print('the_user', the_user)
    if not the_user:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "the user(id=%d) is not exist" % (data["user_id"])
        }
        return jsonify(error_msg)
    role_connectors = RoleWithUser.get_role_with_user_by_user_id(the_user.id)
    print(111111)
    # print('role_connectors', role_connectors)
    for item in role_connectors:
        print('item', item)
        if item.delete() != 0:
            error_msg = {
                "success": 0,
                "error_code": -6,
                "error_msg": "role relationship delete error"
            }
            return jsonify(error_msg)
    print('ret-qian')
    ret = the_user.delete()
    if ret == -1:
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "database write error"
        }
        return jsonify(error_msg)
    if ret == 0:
        error_msg = {
            "success": 1
        }
        return jsonify(error_msg)
    error_msg = {
        "success": 0,
        "error_code": -5,
        "error_msg": "unknow error"
    }
    return jsonify(error_msg)


@mod.route("/get_users_by_department_id/", methods=["GET", "POST"])
def get_users_by_department_id_interface():
    """
    根据部门id获取此部门所有用户
    """
    # request: json
    # {
    #       id: id
    # }
    # return: json
    # [
    #       {
    #               username: "username",
    #               email: "email",
    #               mobile_phone: "mobile_phone",
    #               password: "password",
    #               safe_code: "safe_code",
    #               sex: sex(int), // 1:男性 0:女性
    #               department_name: "department_name",
    #               company_name: "company_name",
    #               department_id: department_id,
    #               organization_id: organization_id,
    #               roles: ["<role1>","<role2>",...]
    #       }, ...
    # ]
    try:
        data = json.loads(request.data.decode("utf-8"))
        # data = json.loads(request.args.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    if not "id" in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    if not isinstance(data["id"], int):
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "id must be an int"
        }
        return jsonify(error_msg)
    try:
        user_list = User.get_users_by_department_id(data["id"])
        print('user_list', user_list)
    except:
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "database error"
        }
        return jsonify(error_msg)
    rlist = []
    for item in user_list:
        role_str_list = []
        user_roles = Role.get_roles_by_user(item)
        for role in user_roles:
            role_str_list.append(str(role))
        t_dic = User.get_user_dic(item)
        t_dic["roles"] = role_str_list
        t_dic["department_name"] = Department().get_entity_by_id(item.department_id).name
        t_dic["company_name"] = Organization().get_entity_by_id(item.organization_id).name
        rlist.append(t_dic)
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": rlist
    }
    return jsonify(rdic)


@mod.route("/get_users_by_role_id/", methods=["POST"])
def get_users_by_role_id_interface():
    """
    根据角色id获取用户
    """
    # request: json
    # {
    #       id:id
    # }
    # return: json
    # [
    #       {
    #               username: "username",
    #               email: "email",
    #               mobile_phone: "mobile_phone",
    #               password: "password",
    #               safe_code: "safe_code",
    #               sex: sex(int), // 1:男性 0:女性
    #               department_name: "department_name",
    #               company_name: "company_name",
    #               department_id: department_id,
    #               organization_id: organization_id,
    #               roles: ["<role1>","<role2>",...]
    #       }, ...
    # ]
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    if not "id" in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    if not isinstance(data["id"], int):
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "id must be an int"
        }
        return jsonify(error_msg)
    try:
        user_list = User.get_users_by_role_id(data["id"])
    except Exception as err:
        print(err)
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "未知错误"
        }
        return jsonify(error_msg)
    rlist = []
    for the_user in user_list:
        role_str_list = []
        user_roles = Role.get_roles_by_user(the_user)
        for role in user_roles:
            role_str_list.append(str(role))
        t_dic = User.get_user_dic(the_user)
        t_dic["roles"] = role_str_list
        rlist.append(t_dic)
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": rlist
    }
    return jsonify(rdic)


@mod.route("/get_users_by_organization_id/", methods=["GET", "POST"])
def get_user_by_organization_id_interface():
    """
    根据机构id获取此机构的所有用户
    """
    # request: json
    # {
    #       id: id
    # }
    # return: json
    # [
    #       {
    #               quarter_name
    #               quarter_id
    #               username: "username",
    #               email: "email",
    #               mobile_phone: "mobile_phone",
    #               password: "password",
    #               safe_code: "safe_code",
    #               sex: sex(int), // 1:男性 0:女性
    #               department_id: department_id,
    #               organization_id: organization_id,
    #               roles: ["<role1>","<role2>",...]
    #       }, ...
    # ]
    if request.method == "POST":
        try:
            data = json.loads(request.data.decode("utf-8"))
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json format error"
            }
            return jsonify(error_msg)
    if request.method == "GET":
        org_id = request.args.get("org_id", type=int)
        data = {}
        data["id"] = org_id
    if not "id" in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    if not isinstance(data["id"], int):
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "id must be an int"
        }
        return jsonify(error_msg)
    try:
        user_list = User.get_users_by_organization_id(data["id"])
        print(11, user_list)
        # department_ids = Department.get_departments_all_by_organization_id(data["id"])
        # print('department_ids', department_ids)
        # print(22, department_ids)
    except:
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "database error"
        }
        return jsonify(error_msg)
    rlist = []
    for item in user_list:
        role_int_list = []
        role_str_list = []
        # 角色列表
        user_roles = Role.get_roles_by_user(item)
        for role in user_roles:
            role_int_list.append(role.id)
            role_str_list.append(role.name)
        t_dic = User.get_user_dic(item)
        t_dic["roles"] = role_str_list
        t_dic["roles_id"] = role_int_list
        rlist.append(t_dic)
    # for department in department_ids:
        # quarter_id_list = []
        # quarter_name_list = []
        # quarters = Quarter.get_all_quarters_by_department_id(department.id)
        # for quarter in quarters:
            # quarter_id_list.append(quarter.id)
            # quarter_name_list.append(quarter.name)
            # t_dic["quarter"] = quarter.name
            # t_dic["quarter_id"] = quarter.id
            # rlist.append(t_dic)
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": rlist
    }
    return jsonify(rdic)


@mod.route("/add_roles_to_user/", methods=["POST"])
def add_roles_to_user_interface():
    """
    为指定id的用户增添指定id的角色
    """
    # request: json
    # {
    #       user_id: user_id,
    #       roles: [role_id, ...]
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "数据格式错误"
        }
        return jsonify(error_msg)
    try:
        user_id = data["user_id"]
        roles = data["roles"]
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "数据不完整"
        }
        return jsonify(error_msg)
    if not isinstance(user_id, int):
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "user_id must be an int"
        }
        return jsonify(error_msg)
    if not isinstance(roles, list):
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "roles must be a list"
        }
        return jsonify(error_msg)
    the_user = User.get_user_by_id(user_id)
    if not the_user:
        error_msg = {
            "success": 0,
            "error_code": -5,
            "error_msg": "user(id=%d) is not exist" % user_id
        }
        return jsonify(error_msg)
    for role in data["roles"]:
        if not isinstance(role, int):
            error_msg = {
                "success": 0,
                "error_code": -6,
                "error_msg": "role_id must be an int"
            }
            return jsonify(error_msg)
        t_role = Role.get_role_by_id(role)
        if not t_role:
            error_msg = {
                "success": 0,
                "error_code": -7,
                "error_msg": "role(id=%d) is not exist" % role
            }
            return jsonify(error_msg)
        if User.add_roles_to_user(the_user, [t_role]) != 0:
            error_msg = {
                "success": 0,
                "error_code": -8,
                "error_msg": "build relationship between user(id=%d) and role(id=%d)" % (the_user.id, t_role.id)
            }
            return jsonify(error_msg)
    error_msg = {
        "success": 1
    }
    return jsonify(error_msg)

# 我加的方法8月27
@mod.route("/add_users_to_role/", methods=["POST"])
def add_users_to_role():
    """
    为指定id的角色增添指定id的用户
    """
    # request: json
    # {
    #       role_id: role_id,
    #       users: [user_id, ...]
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "数据格式错误"
        }
        return jsonify(error_msg)
    try:
        role_id = data["role_id"]
        users = data["users"]
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "数据不完整"
        }
        return jsonify(error_msg)
    if not isinstance(role_id, int):
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "role_id must be an int"
        }
        return jsonify(error_msg)
    if not isinstance(users, list):
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "users must be a list"
        }
        return jsonify(error_msg)
    the_role = Role.get_role_by_id(role_id)
    if not the_role:
        error_msg = {
            "success": 0,
            "error_code": -5,
            "error_msg": "role(id=%d) is not exist" % role_id
        }
        return jsonify(error_msg)
    for user in data["users"]:
        if not isinstance(user, int):
            error_msg = {
                "success": 0,
                "error_code": -6,
                "error_msg": "user_id must be an int"
            }
            return jsonify(error_msg)
        t_user = User.get_user_by_id(user)
        if not t_user:
            error_msg = {
                "success": 0,
                "error_code": -7,
                "error_msg": "user(id=%d) is not exist" % user
            }
            return jsonify(error_msg)
        if User.add_users_to_role(the_role, [t_user]) != 0:
            error_msg = {
                "success": 0,
                "error_code": -8,
                "error_msg": "build relationship between user(id=%d) and role(id=%d)" % (the_role.id, t_user.id)
            }
            return jsonify(error_msg)
    error_msg = {
        "success": 1
    }
    return jsonify(error_msg)


@mod.route("/delete_role_with_user/", methods=["POST"])
def delete_role_with_user_interface():
    """
    根据用户id和权限id删除指定用户的指定角色
    """
    # request: json
    # {
    #       user_id: user_id,
    #       role_id: role_id
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    try:
        user_id = data["user_id"]
        role_id = data["role_id"]
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    if not isinstance(user_id, int):
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "user_id must be an int"
        }
        return jsonify(error_msg)
    if not isinstance(role_id, int):
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "role_id must be an int"
        }
        return jsonify(error_msg)
    the_user = User.get_user_by_id(user_id)
    if not the_user:
        error_msg = {
            "success": 0,
            "error_code": -5,
            "error_msg": "user(id=%d) is not exist" % user_id
        }
        return jsonify(error_msg)
    the_role = Role.get_role_by_id(role_id)
    if not the_role:
        error_msg = {
            "success": 0,
            "error_code": -6,
            "error_msg": "role(id=%d) is not exist" % role_id
        }
        return jsonify(error_msg)
    connector = RoleWithUser.get_role_with_user(user_id, role_id)
    print('connector', connector)
    if not connector:
        error_msg = {
            "success": 0,
            "error_code": -7,
            "error_msg": "user(id=%d) do not have role(id=%d)" % (user_id, role_id)
        }
        return jsonify(error_msg)
    ret = connector.delete()
    if ret == -1:
        error_msg = {
            "success": 0,
            "error_code": -8,
            "error_msg": "database error"
        }
        return jsonify(error_msg)
    if ret == 0:
        error_msg = {
            "success": 1
        }
        return jsonify(error_msg)
    error_msg = {
        "success": 0,
        "error_code": -9,
        "error_msg": "unknow error"
    }
    return jsonify(error_msg)

# 我的测试方法
@mod.route("/get_u/", methods=["GET", "POST"])
def get_u():
    data = json.loads(request.data.decode("utf-8"))

    ddd = RoleWithUser.get_role_with_user_by_user_id(data['u_id'])
    # di = {}
    # di['li'] = []
    # for i in usss:
    #     print('i',i)
    #     print('类型', type(i))
    #     di['li'].append(dict(i))
    return ddd


@mod.route("/get_role_all/", methods=["GET", "POST"])
def get_role_all_interface():
    """
    获取所有角色
    """
    # return: json
    # [
    #   {
    #       id:id,
    #       name:"name",
    #       code:"code",
    #       description:"description",
    #       status:"status"
    #   }, ...
    # ]
    roles = Role.get_role_all()
    rlist = []
    for item in roles:
        rlist.append(Role.get_role_dic(item))
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": rlist
    }
    return jsonify(rdic)


@mod.route("/add_role/", methods=["POST"])
def add_role_interface():
    """
    新建角色
    """
    # request: json
    # {
    #       name:"name"(必填),
    #       code:"code"(必填),
    #       description:"description",
    #       status:status
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    try:
        name = data["name"]
        code = data["code"]
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "erro_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    # buttons=[]
    # if not isinstance(button_list,list):
    #     error_msg={
    #                     "success":0,
    #                     "error_code":-5,
    #                     "error_msg":"buttons must be a list"
    #             }
    #     return jsonify(error_msg)
    # for item in button_list:
    #     the_button=get_button_by_id(item)
    #     if not the_button:
    #         error_msg={
    #                         "success":0,
    #                         "error_code":-3,
    #                         "error_msg":"button is not exist"
    #                 }
    #         return jsonify(error_msg)
    #     buttons.append(the_button)
    if "description" in data:
        description = data["description"]
    else:
        description = None
    if "status" in data:
        status = data["status"]
    else:
        status = None
    # if buttons==[]:
    #     buttons=None
    if Role.get_role_by_name(name) is not None:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "角色名称已被占用"
        }
        return jsonify(error_msg)
    if Role.get_role_by_code(code) is not None:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "角色编码已被占用"
        }
        return jsonify(error_msg)
    ret = Role.add_role(name=name, code=code, description=description, status=status, buttons=[])
    if ret != 0:
        error_msg = {
            "success": 0,
            "error_code": -4,
            "error_msg": "database error"
        }
        return jsonify(error_msg)
    error_msg = {
        "success": 1
    }
    return jsonify(error_msg)


@mod.route("/edit_role/", methods=["POST"])
def edit_role_interface():
    """
    编辑角色
    """
    # request: json
    # {
    #       id:id,
    #       name:"name",
    #       code:"code",
    #       description:"description",
    #       status:status
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    try:
        id_num = data["id"]
        name = data["name"]
        code = data["code"]
        description = data["description"]
        # status = data["status"]
        status = data.get('status', 1)
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    the_role = Role.get_role_by_id(id_num)
    if the_role is None:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "role is not exist"
        }
        return jsonify(error_msg)
    if name != the_role.name:
        if not Role.get_role_by_name(name) is None:
            error_msg = {
                "success": 0,
                "error_code": -4,
                "error_msg": "角色名称已存在"
            }
            return jsonify(error_msg)
        the_role.name = name
    if code != the_role.code:
        if not Role.get_role_by_code(code) is None:
            error_msg = {
                "success": 0,
                "error_code": -5,
                "error_msg": "角色编码已存在"
            }
            return jsonify(error_msg)
        the_role.code = code
    if description != the_role.description:
        the_role.description = description
    if status != the_role.status:
        the_role.status = status
    if the_role.save() != 0:
        error_msg = {
            "success": 0,
            "error_code": -6,
            "error_msg": "role save error"
        }
        return jsonify(error_msg)
    error_msg = {
        "success": 1
    }
    return jsonify(error_msg)


@mod.route("/delete_role/", methods=["POST"])
def delete_role_interface():
    """
    删除角色
    """
    # request: json
    # {
    #       id:id
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    if not "id" in data:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    the_role = Role.get_role_by_id(data["id"])
    if the_role is None:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "role is not exist"
        }
        return jsonify(error_msg)
    connector = RoleWithUser.get_role_with_user_by_role_id(data["id"])
    # role_connectors = RoleWithUser.get_role_with_user_by_role_id(the_role.id)
    user_id_list = []
    for item in connector:
        user_id_list.append(item.user_id)
    if len(connector) != 0:
        error_msg = {
            "success": 0,
            "error_code": -4,
            # "error_msg": "user(id=%s) steal deppend on this role" % (str(user_id_list))
            "error_msg": "该角色下有用户,不能删除"
        }
        return jsonify(error_msg)
    ret = the_role.delete()
    if ret != 0:
        error_msg = {
            "success": 0,
            "error_code": -5,
            "error_msg": "role delete error"
        }
        return jsonify(error_msg)
    error_msg = {
        "success": 1
    }
    return jsonify(error_msg)


@mod.route("/add_buttons_to_role/", methods=["POST"])
def add_buttons_to_role_interface():
    """
    向指定角色添加指定按钮
    """
    # request: json
    # {
    #       role_id:role_id,
    #       buttons:[button_id_1,button_id_2]
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    try:
        role_id = data["role_id"]
        buttons = data["buttons"]
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    if (not isinstance(role_id, int) or (not isinstance(buttons, list))):
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    the_role = Role.get_role_by_id(role_id)
    if the_role is None:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "指定角色不存在"
        }
        return jsonify(error_msg)
    button_list = []
    for item in buttons:
        button_list.append(Button.get_button_by_id(item))
    RoleWithButton.add_buttons_to_role(the_role, button_list)
    error_msg = {
        "success": 1,
        "error_code": None,
        "error_msg": None
    }
    return jsonify(error_msg)


@mod.route("/add_modules_to_role/", methods=["POST"])
def add_modules_to_role():
    """
    为角色添加模块
    """
    # request: json
    # {
    #   "role_id": 1,
    #   "modules": [1,2]
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json format error"
        }
        return jsonify(error_msg)
    try:
        role_id = data["role_id"]
        modules = data["modules"]
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "key of json is not complete"
        }
        return jsonify(error_msg)
    the_role = Role.get_role_by_id(role_id)
    if the_role is None:
        error_msg = {
            "success": 0,
            "error_code": -3,
            "error_msg": "data in json is wrong"
        }
        return jsonify(error_msg)
    t_module_id_list=[]
    for module_id in modules:
        the_module = Module.get_module_by_id(module_id)
        children = Module.query.filter(Module.path.like("%,"+str(the_module.id)+",%")).all()
        print("children: %s" %str(children))
        for item in children:
            t_module_id_list.append(item.id)
        if the_module is None:
            error_msg = {
                "success": 0,
                "error_code": -3,
                "error_msg": "data in json is wrong"
            }
            return jsonify(error_msg)
    for item in t_module_id_list:
        # 建立角色与模块的"."按钮的联系
        buttonConnector = RoleWithButton()
        buttonConnector.role_id = role_id
        buttonConnector.button_id = Button.query.filter(Button.module_id == item, Button.name == ".").first().id
        if buttonConnector.save()!=0:
            error_msg = {
                "success": 0,
                "error_code": -4,
                "error_msg": "server error"
            }
            return jsonify(error_msg)
    rdic={}
    rdic["success"]=1
    rdic["error_code"]=None
    rdic["error_msg"]=None
    rdic["data"]=[]
    return jsonify(rdic)


@mod.route("/get_system_view/", methods=["POST"])
def get_system_view():
    """
    获取所有的系统视图
    """
    data = {}  # data={"表名":["字段名", ...], ...}
    # 获取所有表名
    all_tablename_list = execute_sql("show tables;").fetchall()
    for item in all_tablename_list:
        data[item[0]] = []
    # 获取所有字段名
    for t_item in all_tablename_list:
        all_column = execute_sql("desc %s;" % (t_item[0])).fetchall()
        for in_t_item in all_column:
            data[t_item[0]].append(in_t_item[0])
    print(data)
    rdic = {
        "success": 1,
        "error_code": None,
        "error_msg": None,
        "data": [data]
    }
    return jsonify(rdic)


@mod.route("/search/", methods=["POST"])
def user_search():
    """
    模糊搜索接口
    """
    # request: json
    # {
    #       "query_word":"query_word"
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json格式错误"
        }
        return jsonify(error_msg)
    if "query_word" in data:
        query_word = data["query_word"]
    else:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "数据不完整"
        }
        return jsonify(error_msg)
    rdic = User.search(query_word)
    return jsonify(rdic)


@mod.route("/search_role/", methods=["POST"])
def role_search():
    """
    模糊搜索接口
    """
    # request: json
    # {
    #       "query_word":"query_word"
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json格式错误"
        }
        return jsonify(error_msg)
    if "query_word" in data:
        query_word = data["query_word"]
    else:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "数据不完整"
        }
        return jsonify(error_msg)
    rdic = Role.search(query_word)
    return jsonify(rdic)

# 以下方法address:枣庄,author:rui
@mod.route("/disable_user/", methods=["GET", "POST"])
def disable_user():
    """
    禁用账户
    {id: 56}
    :return:
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json格式错误"
        }
        return jsonify(error_msg)
    try:
        the_user = User.get_user_by_id(data['id'])
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "该用户不存在"
        }
        return jsonify(error_msg)
    status = the_user.status
    if status == 0:
        return jsonify({
            "success": 0,
            "error_code": -3,
            "error_msg": "该用户已禁用"
        })
    the_user.status = 0
    the_user.save()
    error_msg = {
        "success": 1,
        "error_code": None,
        "error_msg": None
    }
    return jsonify(error_msg)

@mod.route("/enable_user/", methods=["GET", "POST"])
def enable_user():
    """
    启用账户
    {id: 56}
    :return:
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json格式错误"
        }
        return jsonify(error_msg)
    try:
        the_user = User.get_user_by_id(data['id'])
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "该用户不存在"
        }
        return jsonify(error_msg)
    status = the_user.status
    if status == 1:
        return jsonify({
            "success": 0,
            "error_code": -3,
            "error_msg": "该用户已启用"
        })
    the_user.status = 1
    the_user.save()
    error_msg = {
        "success": 1,
        "error_code": None,
        "error_msg": None
    }
    return jsonify(error_msg)


@mod.route("/reset_password/", methods=["GET", "POST"])
def reset_password():
    """
    启用账户
    {id: 56}
    :return:
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        error_msg = {
            "success": 0,
            "error_code": -1,
            "error_msg": "json格式错误"
        }
        return jsonify(error_msg)
    try:
        the_user = User.get_user_by_id(data['id'])
    except:
        error_msg = {
            "success": 0,
            "error_code": -2,
            "error_msg": "该用户不存在"
        }
        return jsonify(error_msg)
    old_password = the_user.password
    print('old_password', old_password)
    new_password = '123456'
    new_password = hashlib.md5(new_password.encode("utf-8")).hexdigest()  # 新密码做hash
    print('new_password', new_password)
    the_user.password = new_password
    the_user.save()
    error_msg = {
        "success": 1,
        "error_code": None,
        "error_msg": None
    }
    return jsonify(error_msg)

